package com.yy.micro.magic.core.context;

import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author YY
 * @version 1.0.0
 * @update 2021/9/18 9:51 下午
 * @description: 资源管理器，Magic Cube中需要的外部资源，如变换规则数据，码表数据等。通常在应用启动完成后加载指定的静态资源，与{@link com.yy.micro.magic.core.loader.ResourceLoader}配合使用。
 */
@Component
public class ResourceManager implements ResourceFactory<Class,ResourceFactory>{

    private Map<Class,ResourceFactory> resources = new ConcurrentHashMap<>();

    /**
     * @description: 保存资源内容，覆盖
     * @param key 通常为资源加载器{@link com.yy.micro.magic.core.loader.ResourceLoader}
     * @param name 自定义资源名
     * @param value  资源内容
     * @return
     * @update 2021/9/18
     */
    public void set(Class key,String name,Object value){
        ResourceFactory factory =null;
        if (resources.containsKey(key)){
            factory = resources.get(key);
        }else{
            factory = ResourceFactory.Impl.create();
            resources.put(key,factory);
        }
        factory.set(name,value);
    }

    @Override
    public void set(final Class key, final ResourceFactory value) {
        resources.put(key,value);
    }
    /**
     * @description: 保存资源内容，追加
     * @param key 通常为资源加载器{@link com.yy.micro.magic.core.loader.ResourceLoader}
     * @param name 自定义资源名
     * @param value  资源内容
     * @return
     * @update 2021/9/18
     */
    public void add(Class key,String name,Object value){
        ResourceFactory factory =null;
        if (resources.containsKey(key)){
            factory = resources.get(key);
        }else{
            factory = ResourceFactory.Impl.create();
            resources.put(key,factory);
        }
        factory.add(name,value);
    }

    @Override
    public void add(final Class key, final ResourceFactory value) {
        if (!resources.containsKey(key)){
            resources.put(key,value);
        }
    }

    @Override
    public ResourceFactory getValue(final Class key) {
        return resources.get(key);
    }

    @Override
    public <T> T getValue(final Class key, final Class<T> cls) {
        throw new RuntimeException("no value") ;
    }

    public <T> T getValue(Class key,String key1,Class<T> cls){
        ResourceFactory factory = getValue(key);
        if (factory != null) {
            return (T) factory.getValue(key1,cls);
        }
        return null;
    }
}

